<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Jobs\SendUserQrcode;
use App\Orderall;
use App\Qrcode;
use App\User;
use App\UserCoin;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class UserController extends Controller
{
    protected $wechat;

    public function __construct()
    {
        $this->wechat = app('wechat');
    }

    /**
     * @function 二维码列表
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function qrcode_list()
    {
        $data = [];
        $data['qrcodes'] = Qrcode::select(['id', 'name', 'thumbnail'])->get();

        return response()->json(['code' => 1000, 'data' => $data]);
    }

    /**
     * @function 生成二维码
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function qrcode(Request $request)
    {
        $user = auth()->user();

        $qrcode_id = $request->input('qrcode', 1);
        $qrcode = Qrcode::find($qrcode_id);

        dispatch(new SendUserQrcode($user, $qrcode));

        return response()->json(['code' => 1000, 'msg' => '已提交到队列，请稍后']);
    }

    /**
     * @function 获取用户账户详情
     *
     * @param Request $request
     * @return $this
     */
    public function center(Request $request)
    {
        $user = auth()->user();
        $user->fan_count = User::where('finder_id', $user->id)->count();

        $user = json_decode($user, true);

        $user['JB'] = UserCoin::totalJb($user['id']);
        $user['ZS'] = UserCoin::totalZs($user['id']);
        $user['XYX'] = UserCoin::totalXyx($user['id']);

        $user['income'] = UserCoin::where('user_id', $user['id'])->where('type', 2)->where('coin', '>', 0)->sum('coin');
        $user['team'] = [
            'count' => $user['fan_count'],
            'total' => Orderall::whereIn('user_id', User::where('finder_id', $user['id'])->pluck('id'))->where('status', 1)->sum('total'),
        ];

        return response()->json(['code' => 1000, 'data' => $user])->withCallback($request->input('callback'));
    }

    /**
     * @fucntion 发送验证码
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendcode(Request $request)
    {
        $user = auth()->user();

        $phone = trim($request->input('phone'));

        if (!preg_match("/1[34578]{1}\d{9}$/", preg_replace("/\s/", "", trim($phone)))) {
            return response()->json(['code' => 1001, 'msg' => '请填写正确的手机号']);
        }

        $key = 'user_send_code_' . $user->id;
        if (Redis::ttl($key) > 60) {
            return response()->json(['code' => 1002, 'msg' => '请60秒后再发起验证码']);
        }

        if (User::where('phone', $phone)->exists()) {
            return response()->json(['code' => 1003, 'msg' => '该手机号已绑定其他账户']);
        }

        $code = rand(100000, 999999);

        Redis::setex($key, 120, $phone . '_' . $code);

        try {
            $message = '您的验证码是' . $code . '，有效期2分钟，若非本人操作，请勿泄露。【欢乐菠萝】';
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "http://sms-api.luosimao.com/v1/send.json");
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 8);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_USERPWD, 'api:key-5145112f10b704bbd5592f80402c77b5');
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, array('mobile' => $phone, 'message' => $message));
            $res = curl_exec($ch);
            curl_close($ch);
        } catch (\Exception $e) {
        }

        return response()->json(['code' => 1000, 'res' => $res]);
    }

    /**
     * @function 验证验证码
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkcode(Request $request)
    {
        $user = auth()->user();
        $phone = $request->input('phone');
        $code = $request->input('code');

        $key = 'user_send_code_' . $user->id;

        if (!Redis::exists($key)) {
            return response()->json(['code' => 1001, 'msg' => '该验证码已过期，请重新获取验证码']);
        }

        if (Redis::get($key) != $phone . '_' . $code) {
            return response()->json(['code' => 1002, 'msg' => '验证码错误']);
        }

        if (User::where('phone', $phone)->exists()) {
            return response()->json(['code' => 1003, 'msg' => '该手机号已绑定其他账户']);
        }

        $user->phone = $phone;
        $user->save();

        $user->update(['status' => DB::raw('status|2')]);

        return response()->json(['code' => 1000]);
    }

    /**
     * @function 获取粉丝信息
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function fan(Request $request)
    {
        $user = auth()->user();

        $query = User::where('finder_id', $user->id)->select(['avatar', 'nickname', 'status', 'province', 'city'])->orderBy('status');
        if ($request->input('valid', 0) == 1) {
            $query->whereRaw('status&7=7');
        }

        $fans = $query->paginate(10);

        return response()->json(['code' => 1000, 'data' => $fans]);
    }

    /**
     * @function 获取用户状态
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function status()
    {
        $data = [];

        $user = auth()->user();

        $data['status'] = $user->status;

        return response()->json(['code' => 1000, 'data' => $data]);
    }
    
}
